package org.yzh.scheduler.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzh.commons.model.PageInfo;
import org.yzh.commons.model.Pagination;
import org.yzh.commons.util.DateUtils;
import org.yzh.commons.util.EncryptUtils;
import org.yzh.scheduler.mapper.JobLogMapper;
import org.yzh.scheduler.model.entity.JobLogDO;
import org.yzh.scheduler.model.vo.LogKey;

import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;

@Service
public class JobLogService {

    @Autowired
    private JobLogMapper jobLogMapper;

    public Pagination<JobLogDO> find(String name, String group, LocalDateTime startTime, LocalDateTime endTime, PageInfo pageInfo) {
        List<JobLogDO> logs = jobLogMapper.find(name, group, startTime, endTime, pageInfo);
        return new Pagination(pageInfo, logs);
    }

    public int insert(JobLogDO jobLog) {
        return jobLogMapper.insertSelective(jobLog);
    }

    public int update(JobLogDO jobLog) {
        return jobLogMapper.updateSelective(jobLog);
    }

    public String genKey(String jobGroup, String jobName, Integer logId, LocalDateTime time) {
        long epochMilli = DateUtils.toMilli(time);

        LogKey logKey = new LogKey(jobGroup, jobName, logId, epochMilli);
        byte[] bytes = LogKey.toBytes(logKey);
        bytes = EncryptUtils.encrypt(bytes);

        return Base64.getUrlEncoder().encodeToString(bytes);
    }

    public LogKey parseKey(String jobKey) {
        byte[] bytes = Base64.getUrlDecoder().decode(jobKey);
        bytes = EncryptUtils.decrypt(bytes);
        if (bytes == null)
            return null;
        return LogKey.parse(bytes);
    }

    public void callback(LogKey key, String message) {
        JobLogDO jobLogDO = jobLogMapper.get(key.getLogId());

        if (jobLogDO.getCallbackTime() == null) {

            jobLogDO.setCallbackCode(200);
            jobLogDO.setCallbackMsg(message);
            jobLogDO.setCallbackTime(LocalDateTime.now());

            jobLogMapper.updateSelective(jobLogDO);
        }
    }
}